package cn.wch.ch934xlib.assist;

import cn.wch.ch934xlib.utils.LogUtil;

/**
 * 处理串口接收到的数据，拆包和组包，最终解析为某个串口的数据
 */
public class ReceiveDataAssist {

    private final int frameLength=32;
    private ISerialDataCallback dataCallback;

    public void put(byte[] data,int length){
        int offset=0;
        int res=0;
        int len=0;

        int comNo=0;
        int packLen=0;

        if(data==null ||data.length==0 || data.length<length){
            return ;
        }

        len=Math.min(data.length,length);
        res=len;
        while(offset<len){
            if(res<2){
                LogUtil.d("无法获取帧信息");
                break;
            }
            comNo = data[offset] & 0xff-4;
            packLen=data[offset+1] & 0xff;
            if((packLen==0 || data[offset]==0 || !isValidComNumber(comNo)) ){
                if(res>=32){
                    offset=offset+frameLength;
                    res=len-offset;
                    continue;
                }else {
                    break;
                }
            }else{
                byte[] dst=new byte[packLen];
                System.arraycopy(data,offset+2,dst,0,dst.length);
                if(dataCallback!=null){
                    dataCallback.onSerialData(comNo,dst,dst.length);
                }
                offset=offset+frameLength;
                res=len-offset;
            }
        }
    }

    private boolean isValidComNumber(int comNo){
        return (comNo>=0 && comNo<4);
    }

    public void setSerialDataCallback(ISerialDataCallback dataCallback){
        this.dataCallback=dataCallback;
    }

    public static interface ISerialDataCallback {
        void onSerialData(int serialNumber, byte[] buffer, int length);
    }

}
